# -*- coding: utf-8 -*-

from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools.safe_eval import safe_eval
import datetime


class FinancialRepayInvoice(models.Model):
    _inherit = "account.invoice"
    _description = "金融产品本息偿还"

    # 创建退款发票，用于记录本息偿还明细
    @api.multi
    def create_repay_invoices(self):
        filter_refund = "refund"
        description = u"金融产品本息偿还 "

        # 创建瞬时退款发票对象
        invoice_refund_obj = self.env['account.invoice.refund']
        account_invoice_refund_0 = invoice_refund_obj.create(dict(
            description=description,
            date=datetime.date.today(),
            filter_refund=filter_refund
        ))

        account_invoice_refund_0
        mode='refund'

        inv_obj = self.env['account.invoice']
        xml_id = False

        for form in account_invoice_refund_0:
            created_inv = []
            date = False
            description = False

            # 当前的发票模型
            for inv in inv_obj.browse(self.id):
                if inv.state in ['draft', 'proforma2', 'cancel']:
                    raise UserError(_('Cannot refund draft/proforma/cancelled invoice.'))
                if inv.reconciled and mode in ('cancel', 'modify'):
                    raise UserError(_('Cannot refund invoice which is already reconciled, invoice should be unreconciled first. You can only refund this invoice.'))

                date = form.date or False
                description = form.description or inv.name

                # 利用当前的发票对象，创建（复制）新的发票对象
                refund = inv.refund(form.date_invoice, date, description, inv.journal_id.id)

                # 为新的发票对象添加应付利息产品明细
                self.create_interest_payable(refund.invoice_line_ids)

                refund.compute_taxes()

                created_inv.append(refund.id)

                # （退款）发票创建后，跳转需要用到的视图数据
                xml_id = (inv.type in ['out_refund', 'out_invoice']) and 'action_invoice_tree1' or \
                         (inv.type in ['in_refund', 'in_invoice']) and 'action_invoice_tree2'
        if xml_id:
            result = self.env.ref('account.%s' % (xml_id)).read()[0]
            invoice_domain = safe_eval(result['domain'])
            invoice_domain.append(('id', 'in', created_inv))
            result['domain'] = invoice_domain
            return result
        return True

    # 根据购买的理财产品，计算相关利息，作为商品明细显示到发票明细行中
    def create_interest_payable(self,invoice_line_ids):
        inv_line_obj = self.env['account.invoice.line']

        interest_product = self.env.ref('SCreative_Financial_Order.interest_payable')
        sale_obj  = self.env['sale.order']

        for line in invoice_line_ids:
            order = sale_obj.search([('name', '=', line.origin)], limit=1)

            # 组装发票明细行（应付利息产品组装）
            # 应付利息产品数量都设为1
            # 单价为最终应付利息总额
            # 该借贷产品的应付利息总计 ：购买的份额 * 该借贷产品的年回报率 * 认购期限 ；代码相关表示如下
            # line.price_subtotal * line.product_id.annual_interest * (float(order.subscription_period) / 12)
            invoice_line_data = {
                'invoice_id': line.invoice_id.id,
                'product_id':interest_product.id,
                'quantity': 1.0,
                'account_id': interest_product.property_account_income_id.id,
                'name': u'应付利息总计',
                'price_unit': line.price_subtotal * line.product_id.annual_interest * (float(order.subscription_period) / 12),
            }
            inv_line_obj.sudo().create(invoice_line_data)


